package com.heima.Serivce.impl;

import com.alibaba.fastjson.JSON;
import com.heima.Serivce.ScheduleCilent;
import com.heima.Serivce.WemediaNewScan;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.pojos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@Slf4j
public class WemediaSchedlue implements com.heima.Serivce.WemediaSchedlue {

    @Qualifier("com.heima.Serivce.ScheduleCilent")
    @Autowired
    ScheduleCilent scheduleCilent;

    @Autowired
    WemediaNewScan wemediaNewScan;

//    WmNews添加任务
    @Override
    @Async
    public Boolean AddTask(Integer id, Date publishTime) {
        try
        {
            Task task=new Task();
            task.setExecuteTime(publishTime.getTime());
            task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
            task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
            WmNews wmNews=new WmNews();
            wmNews.setId(id);
            task.setParameters(ProtostuffUtil.serialize(wmNews));
            scheduleCilent.AddTask(task);
            log.info("WmNews添加任务成功");
            return true;

        }catch (Exception e)
        {
            log.error("WmNews添加任务失败");
        }
        return false;
    }


//    拉取任务审核文章
    @Override
//    @Scheduled(fixedRate = 5000)
    //@Scheduled(cron = "0 */1 * * * ?")//每分钟执行一次
    public Boolean ExecuteTask() {
        log.info("接取任务进行文章审核");
        ResponseResult responseResult = scheduleCilent.ExecuteTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType()
                , TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        log.info(responseResult.getErrorMessage());
        if(responseResult.getData()!=null&&responseResult.getCode()==200)
        {
            String jsonString = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(jsonString, Task.class);
            System.out.println(task);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            wemediaNewScan.NewSCan(wmNews);
            log.info("文章审核完成");
            return true;
        }
        return false;
    }
}
